# ORM逻辑链接数据库
# ORM（object reational mapping）对象关系映射
from sqlalchemy import create_engine,Column,Integer,Date,String,Text,ForeignKey# pip install sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,relationship

# 基础结构
Base=declarative_base()
# 构建mysql连接串
mysql_URI='mysql+pymysql://root:root@127.0.0.1/blog_spider?charset=utf8'
engine=create_engine(mysql_URI,echo=False,pool_pre_ping=True,pool_recycle=3600)

# 基础操作对象
class DB_Util(object):
    @staticmethod
    def get_session(url=None):
        Session=sessionmaker(bind=engine)
        session=Session()
        return session

    @staticmethod
    def init_db():
        # 构建表
        Base.metadata.create_all(engine)

class Author(Base):
    __tablename__ = 'author'
    Id = Column(Integer, primary_key=True)
    name=Column(String(50))
    blog_list=relationship('Blog',backref='author_info')

class Category(Base):
    __tablename__ = 'category'
    Id = Column(Integer, primary_key=True)
    name = Column(String(50))
    blog_list = relationship('Blog', backref='category_info')

class Blog(Base):
    __tablename__='blog'
    Id=Column(Integer,primary_key=True)
    title=Column(String(100))# 标题
    contents = Column(Text)  # 内容
    author = Column(Integer,ForeignKey('author.Id'))  # 作者
    category = Column(Integer,ForeignKey('catgeory.Id'))  # 分类
    labels = Column(String(100))  # 标签
    fbrq = Column(Date) # 发布日期
    read_num = Column(Integer,default=0)# 阅读数
    reply_num =Column(Integer,default=0)  # 评论数
    href = Column(String(255)) # 文章链接
    source = Column(String(100))  # 来源